package it.ictdays12.cipcip;

import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.TextView;

public class TableRowAdapter extends ArrayAdapter<TagCounter>{
	
	private LayoutInflater inflater;
	private int resId;
	private List<TagCounter> tags;
	private Context ctx;
	
	public TableRowAdapter(Context context, int viewResourceId, List<TagCounter> items) {
		super(context, viewResourceId, items);
		
		ctx = context;
		inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		resId = viewResourceId;
		tags = items;
	}

	@Override
	public int getCount() {
		return tags.size();
	}

	@Override
	public TagCounter getItem(int position) {
		return tags.get(position);
	}

	@Override
	public long getItemId(int position) {
		return 0;
	}
	
	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		convertView = inflater.inflate(resId, null);

		TagCounter tag = getItem(position);
		
		TextView tvTag = (TextView)convertView.findViewById(R.id.TagTextView);
		tvTag.setText(tag.getTag());
		
		TextView tvTime = (TextView)convertView.findViewById(R.id.TimeElapsedTextView);
		tvTime.setText(tag.formatHour(tag.getTimeElapsed()));
		
		ImageButton googleButton = (ImageButton) convertView.findViewById(R.id.GoogleButton);
		ImageButton twitterButton = (ImageButton) convertView.findViewById(R.id.TwitterButton);
		
		googleButton.setTag((TagCounter) tag);
		twitterButton.setTag((TagCounter) tag);
		
		googleButton.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				String linkNews = "https://www.google.it/search?hl=en&gl=it&tbm=nws&q=" + ((TagCounter)v.getTag()).getTag();
				Intent gNewsIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(linkNews));
				ctx.startActivity(gNewsIntent);
			}
		});
		
		twitterButton.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				String linkTwitter = "https://twitter.com/#!/" + ((TagCounter)v.getTag()).getTag();;
				Intent twitterIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(linkTwitter));
				ctx.startActivity(twitterIntent);
			}
		});
		return convertView;
	}
	
	/*protected void startActivity(Intent intent) {
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		intent.addFlags(Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
		startActivity(intent);
	}*/
}